# -*- coding:utf-8 -*-

from rest_framework import serializers
from document.models import Document, Doctype

  
class DocumentSerializer(serializers.ModelSerializer):
    chip = serializers.SerializerMethodField()  
    category = serializers.SerializerMethodField()  
    
    #chip_name = serializers.ReadOnlyField(source='chip.name')
    class Meta:
        model = Document
        fields = "__all__"
    
    def get_chip(self, obj):  # obj是每条记录
        temp = []
        for chip in obj.chip.all().order_by('name'):
            temp.append(chip.name)
        return temp
    
    def get_category(self, obj):
        if obj.category is not None:
            return obj.category.name
    
    
    
class DoctypeSerializer(serializers.ModelSerializer):
    class Meta:
        model = Doctype
        fields = "__all__"
        
    def to_representation(self, item):
        data = super().to_representation(item)
        data['value'] = str(data['id'])
        data['text'] = str(data['name'])
        date_copy = data.copy()
        for key,value in data.items():
            if not value:
                date_copy.pop(key)
        return date_copy
    